package com.huawei.translate.notification.service;

import com.google.gson.Gson;
import com.huawei.translate.model.Application;
import com.huawei.translate.notification.EmailEntity;
import com.huawei.translate.notification.builders.ApplicationApproveEmailBuilder;
import com.huawei.translate.notification.builders.ApplicationRejectEmailBuilder;
import com.huawei.translate.notification.builders.ApplicationSubmissionEmailBuilder;
import com.huawei.translate.notification.builders.EmailBuilder;
import com.huawei.translate.notification.model.EmailHistory;
import com.huawei.translate.notification.repository.EmailHistoryRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
public class NotificationServiceImpl implements NotificationService {

    @Autowired
    private ApplicationSubmissionEmailBuilder applicationSubmissionEmailBuilder;

    @Autowired
    private ApplicationApproveEmailBuilder applicationApproveEmailBuilder;

    @Autowired
    private ApplicationRejectEmailBuilder applicationRejectEmailBuilder;

    @Autowired
    private EmailHistoryRepository emailHistoryRepository;

    private EmailBuilder emailBuilder;

    private Gson gson = new Gson();

    @Autowired
    private EmailSender emailSender;

    @Override
    public void send(EmailTemplateType template, Application application) {
        instanceEmailBuilder(template);
        EmailEntity emailEntity = emailBuilder.WithApplication(application).build();
        EmailHistory history = new EmailHistory();
        history.setTemplateName(EmailTemplateType.ApplicationSubmission.name());
        history.setContent(gson.toJson(emailEntity));
        history.setStatus(0);
        emailHistoryRepository.save(history);
        emailSender.send(history);
    }

    public void instanceEmailBuilder(EmailTemplateType emailTemplateType) {
        if (emailTemplateType == EmailTemplateType.ApplicationSubmission) {
            this.emailBuilder = applicationSubmissionEmailBuilder;
        } else if (emailTemplateType == EmailTemplateType.ApplicationApproved) {
            this.emailBuilder = applicationApproveEmailBuilder;
        } else if (emailTemplateType == EmailTemplateType.ApplicationRejected) {
            this.emailBuilder = applicationRejectEmailBuilder;
        }
    }

    public EmailBuilder getEmailBuilder() {
        return emailBuilder;
    }

}
